package network;

import java.io.IOException;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class UdpEchoClient {
    private DatagramSocket datagramSocket=null;
    private  String serveIp;
    private int servePort;
    public UdpEchoClient(String serveIp,int srverPort){
        this.serveIp=serveIp;
        this.servePort=srverPort;
        try {
            datagramSocket=new DatagramSocket();
        } catch (SocketException e) {
            throw new RuntimeException(e);
        }
    }
    public void start(){
        System.out.println("客户端启动");
        Scanner scanner=new Scanner(System.in);
        while(true){
            System.out.println("请求发送的数据:");
            String request=scanner.next();
            try {
                DatagramPacket datagramPacket1=new DatagramPacket(request.getBytes(),0,request.getBytes().length,
                        InetAddress.getByName(serveIp),servePort);
                datagramSocket.send(datagramPacket1);
            } catch (UnknownHostException e) {
                throw new RuntimeException(e);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            DatagramPacket datagramPacket2=new DatagramPacket(new byte[4096],4096);
            try {
                datagramSocket.receive(datagramPacket2);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            String respon=new String(datagramPacket2.getData(),0,datagramPacket2.getLength());
            System.out.println(respon);
        }
    }
    public static void main(String[] args) {
        UdpEchoClient udpEchoClient=new UdpEchoClient("127.0.0.1",9090);
        udpEchoClient.start();
    }
}
